# -*- encoding: utf-8 -*-
#import odoo.addons.decimal_precision as dp
from odoo import models, fields, api, _
from odoo.addons import base_cw
from odoo.exceptions import UserError
from odoo.tools.float_utils import float_round, float_compare

class account_cash_flows_statement(models.Model):
    _name = 'account.cash.flows.statement'
    _description = u'现金流量表'
    _order = 'print_sequence'

    period_id = fields.Many2one('account.period', u'期别', ondelete="set null")
    sequence = fields.Integer(u'项次')
    name = fields.Char(u'项目')
    print_sequence = fields.Char(u'行次')
    balance = fields.Float(u'本月数', digits='Amount')
    year_balance = fields.Float(u'本年累计数', digits='Amount')
    master_id = fields.Many2one('account.report.format.designer', u'主档', ondelete="cascade")

    def init(self):
        self._cr.execute("""
                    CREATE OR REPLACE FUNCTION account_cash_flows_statement_write(
                        period_t integer,
                        master_id_t integer,
                        uid_t integer)
                    RETURNS void AS
                    $BODY$
                    /*现金流量表

                    -- DROP FUNCTION account_cash_flows_statement_write(period_t,integer,integer)
                    -- select account_cash_flows_statement_write(9,2,1)
                    -- select *  from account_cash_flows_statement
                    -- delete from account_cash_flows_statement

                    */
                    begin

                        delete from account_cash_flows_statement where master_id=master_id_t;
                        insert into account_cash_flows_statement(period_id,sequence,name,print_sequence,balance,year_balance,create_uid,create_date,master_id)
                        select period_t,a.sequence,a.name,a.print_sequence,a.i1,a.m1,uid_t,(now() at time zone 'UTC'),master_id_t
                          from  account_report_format_designer_line a left join account_report_format_designer b on a.master_id=b.id
                         where b.id=master_id_t
                           and report_type='cash';
                    end;
                    $BODY$
                    LANGUAGE plpgsql VOLATILE
                    COST 100;
                   """)
